package com.examples.service.impl;

import static com.examples.util.ResultCodeEnum.SUCCESS_MKT_0000;

import com.examples.model.OrderQueryRsp;
import com.examples.model.RestfulResponse;
import com.examples.service.ExternalService;
import com.examples.util.CustomException;
import com.examples.util.HttpClientUtils;
import com.examples.util.MessageUtil;
import com.examples.util.ResultCodeEnum;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public final class ExternalServiceImpl implements ExternalService {
    private final Environment environment;

    @Autowired
    public ExternalServiceImpl(Environment environment) {
        this.environment = environment;
    }

    @Override
    public OrderQueryRsp queryOrderInfo(String orderId, String orderLineId) {
        /**
         * 云市场查询实例关联的订单信息地址，可以在application.properties中修改，当前值已经是正式配置，测试中可以修改成其他地址
         */
        String marketplaceQueryOrderUrl = environment.getProperty("marketplace.queryOrder.url");
        if (StringUtils.isEmpty(marketplaceQueryOrderUrl)) {
            log.error("marketplace query order url is not set!");
            throw new CustomException(
                ResultCodeEnum.REQUIRE_PARAMETER.getResultCode(),
                ResultCodeEnum.REQUIRE_PARAMETER.getResultMsg(),
                "marketplaceQueryOrderUrl");
        }
        // TODO ak/sk解密处理，示例代码中没有实现加密，如果存在加密需要在这里进行解密，请自行实现密钥加密保存及解密逻辑
        /**
         * 用于apig鉴权的accesskey，需要在application.properties中修改
         * 获取方式参考：https://support.huaweicloud.com/devg-apisign/api-sign-provide-aksk.html
         */
        String apigAccessKey = environment.getProperty("apig.accessKey");
        if (StringUtils.isEmpty(apigAccessKey)) {
            log.error("there is no ak configured");
            throw new CustomException(
                ResultCodeEnum.REQUIRE_PARAMETER.getResultCode(),
                ResultCodeEnum.REQUIRE_PARAMETER.getResultMsg(),
                "IAM AK");
        }
        /**
         * 用于apig鉴权的secretKey，需要在application.properties中修改
         * 获取方式参考：https://support.huaweicloud.com/devg-apisign/api-sign-provide-aksk.html
         */
        String apigSecretKey = environment.getProperty("apig.secretKey");
        if (StringUtils.isEmpty(marketplaceQueryOrderUrl)) {
            log.error("there is no sk configured");
            throw new CustomException(
                ResultCodeEnum.REQUIRE_PARAMETER.getResultCode(),
                ResultCodeEnum.REQUIRE_PARAMETER.getResultMsg(),
                "IAM SK");
        }
        // 组装查询参数
        Map<String, String> queryParamMap = new HashMap<>();
        queryParamMap.put("orderId", orderId);
        queryParamMap.put("orderLineId", orderLineId);
        // 获取云市场实例关联的订单信息
        OrderQueryRsp orderQueryRsp =
            getMarketPlaceOrder(marketplaceQueryOrderUrl, apigAccessKey, apigSecretKey, queryParamMap);
        if (orderQueryRsp == null) {
            throw new CustomException(
                ResultCodeEnum.OTHER_INNER_ERROR.getResultCode(), "there is no response from marketplace.");
        }
        return orderQueryRsp;
    }

    private OrderQueryRsp getMarketPlaceOrder(
        String marketplaceQueryOrderUrl,
        String apigAccessKey,
        String apigSecretKey,
        Map<String, String> queryParamMap) {
        String marketplaceResponse = null;
        try {
            // 调用云市场的接口，将处理结果上报
            RestfulResponse restfulResponse =
                HttpClientUtils.get(marketplaceQueryOrderUrl, queryParamMap, apigAccessKey, apigSecretKey);

            // 根据云市场返回
            marketplaceResponse = restfulResponse.getResponseContent();
            OrderQueryRsp orderQueryRsp = MessageUtil.stringToObject(marketplaceResponse, OrderQueryRsp.class);

            if (null != orderQueryRsp && SUCCESS_MKT_0000.getResultCode().equals(orderQueryRsp.getResultCode())) {
                log.info("query order marketplace return success! response:{}", marketplaceResponse);
            } else {
                log.error("query order marketplace return failed! response:{}", marketplaceResponse);
            }
            return orderQueryRsp;
        } catch (CustomException e) {
            log.error("query order marketplace return failed catch auth exception!", e);
        }
        return null;
    }
}
